/*
 * @Author: cai.qi 
 * @Date: 2020-01-07 16:27:10 
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-01-09 13:39:38
 */


"use strict";
import { Controller } from "egg";

class TypeController extends Controller {
    checkRegister: { username: { type: string; required: boolean; }; password: { type: string; required: boolean; }; mobile: { type: string; required: boolean; }; };
    constructor(ctx) {
        super(ctx);
        this.checkRegister = {
            username: { type: 'string', required: true },
            password: { type: 'string', required: true },
            mobile: { type: 'number', required: true },
        };
    }

    // ------------------------------ register
    async register() {
        const { ctx } = this;
        const body = ctx.request.body;
        if (!(/^1[34578]\d{9}$/.test(body.mobile))) {
            return ctx.throw("手机号格式错误", 201)
        }
        try {
            body.mobile = Number(body.mobile)
        } catch (error) {
            return ctx.throw('手机号有误', 201);
        }
        if (body.password !== body.checkpassword) {
            return ctx.throw('密码与再次输入的密码不一致', 201);
        }
        ctx.validate(this.checkRegister, body);
        const data = await ctx.service.sevAdmin.register(body);
        ctx.helper.success({ data });
    }

    // ------------------------------ login  
    async login() {
        const { ctx } = this;
        const body = ctx.request.body;
        if (!body.username || !body.password) {
            return ctx.throw('账号或密码为空', 201);
        }
        const data = await ctx.service.sevAdmin.login(body);
        ctx.helper.success({ data });
    }
}

export default TypeController;
